<template>
	<form class="md-form-modal" @submit.stop.prevent="onSubmit">
		<slot/>
	</form>
</template>

<script>
import GConfig, {setProps} from '../common/config';

export default {
	name: 'MdFormModule',
	provide() {
		return {
			mdForm: this
		}
	},
	props: {
		model: Object | Array,
		rules: {
			type: Object,
			default: () => {
				return {}
			}
		},
		inline: Boolean,
		labelWidth: String,
		inlineError: Boolean,
		labelPosition: setProps(String, 'labelPosition', false),
		requiredPosition: setProps(String, 'requiredPosition', false),
		horizontal: Boolean,
		showRequiredTag: {
			type: Boolean,
			default: true
		},
		errors: Array,
		showError: Boolean | Number,
		showOneError: Boolean,
		isTrack: setProps(Boolean, 'isTrack', false)
	},
	data() {
		return {
			formItem: [],
		}
	},
	computed: {},
	created() {
	},
	methods: {
		onSubmit() {
			return new Promise((resolve, reject) => {
				this.validator().then(() => {
					this.$emit('submit');
					resolve();
				}).catch(() => {
					this.$emit('failure');
					reject(new Error('validator failure'));
				});
			})
		},
		async validator() {
			return await new Promise(async (resolve, reject) => {
				let isSuccess = true;
				if (!this.model) {
					return resolve();
				}
				let isTrack = this.isTrack;
				for (let i = 0; i < this.formItem.length; i++) {
					let field = this.formItem[i];
					let success = await field.validator(isTrack);
					if (!success) {
						isTrack = false;
						isSuccess = success;
					}
				}
				if (!isSuccess) {
					return reject();
				}
				return resolve();
			});
		},
		resetError() {
			this.formItem.forEach(item => {
				item.reset();
			});
		},
		addFormItem(item) {
			if (item && item.prop) {
				this.formItem.push(item);
			}
		},
		removeFormItem(item) {
			if (item && item.prop) {
				this.formItem.splice(this.formItem.indexOf(item), 1);
			}
		}
	},
	filters: {},
	watch: {}
}
</script>

<style scoped>
.md-form-modal {
	padding: 10px;
}
</style>
